package com.itheima.response;

import com.itheima.utils.DownLoadUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/*
    中文名文件下载
 */
@WebServlet("/servletResponseDemo6")
public class ServletResponseDemo6 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取下载文件名称
        String filename = req.getParameter("filename");
        System.out.println(filename);

        // 获取文件在服务器的输入流对象
        InputStream is = getServletContext().getResourceAsStream("/img/" + filename);

        // 根据浏览器版本不同,对下载文件中文名进行相应处理
        // 获取浏览器版本头
        String agent = req.getHeader("user-Agent");

        // 对下载文件中文名进行相应处理
        filename =  DownLoadUtils.getFileName(agent,filename);
        System.out.println("编码后: " + filename);

        // 设置响应头: 控制浏览器不要解析了, 以附件下载的方式处理服务器返回的数据
        resp.setHeader("content-Disposition","attachment;filename="+filename);

        // 获取字节输出流
        ServletOutputStream sos = resp.getOutputStream();

        // IO流拷贝
        IOUtils.copy(is,sos);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
